package com.lagou.edu.spring.mybatis;

import com.lagou.edu.spring.annotations.Autowired;
import com.lagou.edu.spring.annotations.Import;
import com.lagou.edu.spring.core.ApplicationContext;
import com.lagou.edu.spring.core.BeanDefinition;
import com.lagou.edu.spring.core.BeanDefinitionRegistry;
import com.lagou.edu.spring.core.BeanFactoryPostProcessor;
import com.lagou.niancheng.core.session.SqlSession;
import com.lagou.niancheng.core.session.SqlSessionFactory;

import java.util.List;

/**
 * MapperBean注解处理
 *
 * @author 大犬
 * @date 2020/4/3
 */
public class MapperBeanParseProcess implements BeanFactoryPostProcessor {

    private SqlSessionFactory sqlSessionFactory;

    public MapperBeanParseProcess(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public void preProcessBeanFactory(BeanDefinitionRegistry beanDefinitionRegistry, ApplicationContext applicationContext) {
        System.out.println("生成所有mapper接口实例对象");
        List<BeanDefinition> allBeanDefinitions = beanDefinitionRegistry.getAllBeanDefinitions();
        allBeanDefinitions.forEach(this::parseMapperBean);
    }

    private void parseMapperBean(BeanDefinition beanDefinition) {
        Class beanType = beanDefinition.getBeanType();
        MapperBean mapperBean = (MapperBean) beanType.getAnnotation(MapperBean.class);
        if (mapperBean != null) {
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Object mapper = sqlSession.getMapper(beanType);
            beanDefinition.setProvideBean(mapper);
        }
    }
}
